package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IPermissionService permissionService;

    @Override
    public String getName() {
        return "MyRealm";
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String)token.getPrincipal();
        //查询数据库是否存在该用户
        Employee employee = employeeService.selectByUsername(principal);
        if(employee!=null){
            //认证信息对象
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(employee.getUsername()),this.getName());
        }
        return null;
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("--------------------");
        Employee employee = (Employee)principals.getPrimaryPrincipal();
        //获取当前登陆用户的id
        Long id = employee.getId();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(employee.getAdmin()){
            info.addStringPermission("*:*");
            info.addRole("ADMIN");
        }else{
            //查询当前登陆用户有哪些角色
            info.addRoles(roleService.selectNameByEmployeeId(id));
            //查询当前登陆用户有哪些权限
            info.addStringPermissions(permissionService.selectByEmployeeId(id));
        }
        return info;
    }


}
